package org.gdstash.ui.font;

import javax.swing.*;
import javax.swing.event.ListSelectionListener;
import javax.swing.text.Document;

public class TextFieldList extends JPanel {
    private int rightMargin;
    private JList<String> jlist;
    private JTextField textField;
    private ListModel<String> model;
    private SelectionListener selectionListener;

    public TextFieldList(final ListModel<String> model) {
        this(model, 10);
    }

    public TextFieldList(final ListModel<String> model, final int rightMargin) {
        this.model = model;
        this.rightMargin = rightMargin;
        this.selectionListener = new SelectionListener();
        this.createPartControl();
    }

    private void createPartControl() {
        final FieldListener fieldListener = new FieldListener();
        new JPanel();
        this.setLayout(new BoxLayout(this, 1));
        this.textField = new JTextField();
        final Document document = this.textField.getDocument();
        document.addDocumentListener(fieldListener);
        this.add(this.textField);
        (this.jlist = new JList<String>(this.model)).addListSelectionListener(this.selectionListener);
        this.jlist.setCellRenderer(new BorderListCellRenderer<>(this.rightMargin));
        this.jlist.setSelectionMode(0);
        final JScrollPane scrollPane = new JScrollPane(this.jlist);
        this.add(scrollPane);
        fieldListener.setList(this.jlist);
        fieldListener.setModel(this.model);
        fieldListener.setSelectionListener(this.selectionListener);
        fieldListener.setTextField(this.textField);
        this.selectionListener.setFieldListener(fieldListener);
        this.selectionListener.setList(this.jlist);
        this.selectionListener.setTextField(this.textField);
    }

    public void setVisibleRowCount(final int count) {
        this.jlist.setVisibleRowCount(count);
    }

    public void setSelectedValue(final Object object) {
        this.jlist.setSelectedValue(object, true);
    }

    public void setSelectedIndex(final int index) {
        this.jlist.setSelectedIndex(index);
    }

    public String getSelectedValue() {
        return this.jlist.getSelectedValue();
    }

    public int getSelectedIndex() {
        return this.jlist.getSelectedIndex();
    }

    public void addListSelectionListener(final ListSelectionListener listener) {
        this.jlist.addListSelectionListener(listener);
    }

    public JList getJList() {
        return this.jlist;
    }

    public JTextField getTextField() {
        return this.textField;
    }
}
